var express = require('express');
var router = express.Router();
var multiparty = require("multiparty")
var util = require("util")
var fs = require("fs")


// var moment = require("moment")
// var { selectAdmin } = require("../db/login.js")

router.post('/upload', function (req, res, next) {
	var form = new multiparty.Form();
	form.encoding = 'utf-8';
	form.uploadDir = './public/uploads';
	form.maxFilesSize = 2 * 1024 * 1024;
	let data = {}
	form.parse(req, function (err, fields, files) {
		if (err) {
			res.send({
				message: "上传失败",
				code: "1"
			})
		} else {
			let file = files.file[0]
			var uploadedPath = file.path;
			let append = file.originalFilename.split(".")[file.originalFilename.split(".").length - 1]

			let timestamp = new Date().getTime();
			var dstPath = `./public/uploads/${timestamp}.${append}`;
			var rtPath = `/uploads/${timestamp}.${append}`;
			fs.rename(uploadedPath, dstPath, function (err) {
				if (err) {
					res.send({
						message: "上传失败",
						code: "2",
					})
				} else {
					res.send({
						message: "上传成功",
						code: "0",
						path: rtPath
					})
				}
			})
		}
	});
})

module.exports = router;
